package com.daoshu.socket.service.impl;

import com.daoshu.socket.constants.Constants;
import com.daoshu.socket.redis.RedisUtil;
import com.daoshu.socket.view.PushMessageIn;
import com.daoshu.socket.bean.UserInfo;
import com.daoshu.socket.service.ISendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName: SendMessageForAll
 * @description: 发送给所有用户
 * @author: Allen
 * @create: 2019-06-25 22:32
 **/
@Component
@Slf4j
public class SendMessageForAll implements ISendMessage {

    /**
     * 引入redis
     */
    @Autowired
    RedisUtil redisUtil;

    /****
     * 发送消息给所有用户
     * @param in
     */
    @Override
    public void sendMessage(PushMessageIn in) {
        List<UserInfo> userInfos = UserSessionManage.getAllUserInfoList();
        if (null == userInfos || userInfos.size() < 1) {
            //saveOfflineMessage(in);
        } else {
            for (UserInfo userInfo : userInfos) {
                if (userInfo.getClient() == null) {
                    log.info("client=null,PushMessageIn={}", in);
                    //saveOfflineMessage(in);
                    continue;
                }
                log.info("SendMessageForAll sendMessage userInfo:{} PushMessageIn:{}", userInfo, in);
                userInfo.getClient().sendEvent(in.getType(), in);
                //delOfflineMessage(in);
            }
        }

    }

    @Override
    public void sendMessageByGroup(PushMessageIn in) {
        if (in.getGroupId() == null || in.getGroupId().isEmpty()) {
            log.info("sendMessageByGroup groupId is null");
            return;
        }
        List<UserInfo> userInfos = UserSessionManage.getUserInfoListByGroupId(in.getGroupId());
        if (null == userInfos || userInfos.size() < 1) {
            //saveOfflineMessage(in);
        } else {
            for (UserInfo userInfo : userInfos) {
                if (userInfo.getClient() == null) {
                    log.info("client=null,PushMessageIn={}", in);
                    //saveOfflineMessage(in);
                    continue;
                }
                log.info("SendMessageForAll sendMessage userInfo:{} PushMessageIn:{}", userInfo, in);
                userInfo.getClient().sendEvent(in.getType(), in);
                //delOfflineMessage(in);
            }
        }

    }

    /**
     * 保存离线消息
     * @param in
     */
    private void saveOfflineMessage(PushMessageIn in) {
        //redisUtil.set(String.format(Constants.MESSAGE_BODY, in.getId()), in,90);
    }

    /**
     * 删除离线消息
     * @param in
     */
    private void delOfflineMessage(PushMessageIn in) {
        //redisUtil.del(String.format(Constants.MESSAGE_BODY, in.getId()));
    }


}
